﻿Public Class frmSettings

    Private Sub frmSettings_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If Not CloseOK Then DialogResult = Windows.Forms.DialogResult.Cancel
    End Sub

    Private Sub frmSettings_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ShowSettings()
    End Sub
    ''' <summary>Displays settings stored in settings</summary>
    Private Sub ShowSettings()
        Select Case My.Settings.StorageLocation
            Case enmDatabaseLocations.CommonApplicationData
                optLocShared.Checked = True
            Case enmDatabaseLocations.ProgramFiles
                optLocProgramFiles.Checked = True
            Case enmDatabaseLocations.UserApllicationData
                optLocPrivate.Checked = True
            Case enmDatabaseLocations.UserDefined
                optLocUserDefined.Checked = True
        End Select
        txtLocUserDefined.Text = My.Settings.StorageUserDefinedLocation
        Select Case My.Settings.IconLocation
            Case enmDatabaseLocations.CommonApplicationData
                optIcoShared.Checked = True
            Case enmDatabaseLocations.ProgramFiles
                optIcoProgramFiles.Checked = True
            Case enmDatabaseLocations.UserApllicationData
                optIcoPrivate.Checked = True
            Case enmDatabaseLocations.UserDefined
                optIcoUserDefined.Checked = True
        End Select
        txtIcoUserDefined.Text = My.Settings.IconUserDefinedLocation
    End Sub

    Private Sub optLocUserDefined_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optLocUserDefined.CheckedChanged
        tlpLocBrowse.Enabled = optLocUserDefined.Checked
    End Sub

    Private Sub cmdCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
        'Me.DialogResult = Windows.Forms.DialogResult.Cancel
        Threading.Thread.CurrentThread.CurrentUICulture = OldUICulture
        Me.Close()
    End Sub
    ''' <summary>If true form is closed due to OK button</summary>
    Private CloseOK As Boolean = False
    Private Sub cmdOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOK.Click
        If ValidateData() AndAlso StoreData() Then
            My.Settings.Save()
            'Me.DialogResult = Windows.Forms.DialogResult.OK
            CloseOK = True
            Me.Close()
        End If
    End Sub
    ''' <summary>Validates all data entered in form</summary>
    ''' <returns>True if all data are valid</returns>
    Private Function ValidateData() As Boolean
        If optIcoUserDefined.Checked AndAlso Not IO.Directory.Exists(txtIcoUserDefined.Text) Then
            If MsgBox(My.Resources.IconDirectoryDoesntExists, MsgBoxStyle.YesNo Or MsgBoxStyle.Exclamation, My.Resources.DirectoryNotFound) Then
                Try
                    IO.Directory.CreateDirectory(txtIcoUserDefined.Text)
                Catch ex As Exception
                    MsgBox(String.Format(My.Resources.FailedToCreateDirectory, txtIcoUserDefined.Text), MsgBoxStyle.Critical, My.Resources.Error_)
                    Return False
                End Try
            Else
                Return False
            End If
        End If
        Return True
    End Function
    ''' <summary>Stores all data into settings and other places</summary>
    Private Function StoreData() As Boolean
        'Database location
        Dim NewStorageLocation As enmDatabaseLocations
        Select Case True
            Case optLocPrivate.Checked : NewStorageLocation = enmDatabaseLocations.UserApllicationData
            Case optLocProgramFiles.Checked : NewStorageLocation = enmDatabaseLocations.ProgramFiles
            Case optLocShared.Checked : NewStorageLocation = enmDatabaseLocations.CommonApplicationData
            Case Else : NewStorageLocation = enmDatabaseLocations.UserDefined
        End Select
        If NewStorageLocation <> My.Settings.StorageLocation OrElse (NewStorageLocation = enmDatabaseLocations.UserApllicationData AndAlso txtLocUserDefined.Text <> My.Settings.StorageUserDefinedLocation) Then
            Dim OldStorageLocationPath As String = StorageLocation(My.Settings.StorageLocation, My.Settings.StorageUserDefinedLocation)
            Dim NewStorageLocationpath As String = StorageLocation(NewStorageLocation, txtLocUserDefined.Text)
            Try
                If IO.File.Exists(NewStorageLocationpath) Then
                    Select Case MsgBox(My.Resources.DoYouWantToUseContemporaryFileFromNewLoacation, MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question, My.Resources.CopyDatabase)
                        Case MsgBoxResult.Yes
                            IO.File.Delete(NewStorageLocationpath)
                            IO.File.Copy(OldStorageLocationPath, NewStorageLocationpath)
                        Case MsgBoxResult.No
                        Case Else : Return False
                    End Select
                Else
                    IO.File.Copy(OldStorageLocationPath, NewStorageLocationpath)
                End If
            Catch ex As Exception
                MsgBox(My.Resources.FailedToMoveDatabaseToNewLocation & vbCrLf & ex.Message, MsgBoxStyle.Critical, My.Resources.Error_)
                Return False
            End Try
            If MsgBox(My.Resources.DoYouWantToKeepOldDatabase, MsgBoxStyle.Question Or MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2, My.Resources.CopyDatabase) = MsgBoxResult.No Then
                Try
                    IO.File.Delete(OldStorageLocationPath)
                Catch ex As Exception
                    MsgBox(My.Resources.OldFileWasNotDeletedDueToError & vbCrLf & ex.Message, MsgBoxStyle.Exclamation, My.Resources.Error_)
                End Try
            End If
        End If
        My.Settings.StorageLocation = NewStorageLocation
        My.Settings.StorageUserDefinedLocation = txtLocUserDefined.Text
        Select Case True
            Case optIcoPrivate.Checked : My.Settings.IconLocation = enmDatabaseLocations.UserApllicationData
            Case optIcoProgramFiles.Checked : My.Settings.IconLocation = enmDatabaseLocations.ProgramFiles
            Case optIcoShared.Checked : My.Settings.IconLocation = enmDatabaseLocations.CommonApplicationData
            Case optIcoUserDefined.Checked : My.Settings.IconLocation = enmDatabaseLocations.UserDefined
        End Select
        My.Settings.IconUserDefinedLocation = txtIcoUserDefined.Text

        My.Settings.UICulture = CType(cmbLanguage.SelectedItem, Globalization.CultureInfo).Name
        If My.Settings.UICulture <> OldUICulture.Name Then MsgBox("You should restart application in order all strings to be affected with change of language.", MsgBoxStyle.Exclamation, "Language change")
        Return True
    End Function

    Private Sub cmdLocBw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLocBw.Click
        sfdLocBw.FileName = txtLocUserDefined.Text
        If sfdLocBw.ShowDialog = Windows.Forms.DialogResult.OK Then
            txtLocUserDefined.Text = sfdLocBw.FileName
        End If
    End Sub

    Private Sub optIcoUserDefined_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optIcoUserDefined.CheckedChanged
        tlpIcoBrowse.Enabled = optIcoUserDefined.Checked
    End Sub
    Private OldUICulture As Globalization.CultureInfo
    '''<summary>CTor</summary>
    Public Sub New()
        OldUICulture = Threading.Thread.CurrentThread.CurrentUICulture
        InitializeComponent()

        If My.Application.IsNetworkDeployed Then
            lblClickOnce.Text = My.Resources.IsClickOnce
        Else
            lblClickOnce.Text = My.Resources.IsNotClickOnce
        End If

        Dim ProgramFilesDBLocation As Tools.IOt.Path = StorageLocation(enmDatabaseLocations.ProgramFiles, "")
        cmdDBProgramFiles.Tag = ProgramFilesDBLocation - 1
        totHelp.SetToolTip(cmdDBProgramFiles, ProgramFilesDBLocation.Path & vbCrLf & My.Resources.ClickForBrowse)
        Dim AppDataDBLocation As Tools.IOt.Path = StorageLocation(enmDatabaseLocations.UserApllicationData, "")
        cmdDBUser.Tag = AppDataDBLocation - 1
        totHelp.SetToolTip(cmdDBUser, AppDataDBLocation.Path & vbCrLf & My.Resources.ClickForBrowse)
        Dim SharedDBLocation As Tools.IOt.Path = StorageLocation(enmDatabaseLocations.CommonApplicationData, "")
        cmdDBShared.Tag = SharedDBLocation - 1
        totHelp.SetToolTip(cmdDBShared, SharedDBLocation.Path & vbCrLf & My.Resources.ClickForBrowse)

        Dim ProgramFilesIcoLocation As Tools.IOt.Path = IconsLocation(enmDatabaseLocations.ProgramFiles, "")
        cmdIcoProgramFiles.Tag = ProgramFilesIcoLocation
        totHelp.SetToolTip(cmdIcoProgramFiles, ProgramFilesIcoLocation.Path & vbCrLf & My.Resources.ClickForBrowse)
        Dim AppDataIcoLocation As Tools.IOt.Path = IconsLocation(enmDatabaseLocations.UserApllicationData, "")
        cmdIcoUser.Tag = AppDataIcoLocation
        totHelp.SetToolTip(cmdIcoUser, AppDataIcoLocation.Path & vbCrLf & My.Resources.ClickForBrowse)
        Dim SharedIcoLocation As Tools.IOt.Path = IconsLocation(enmDatabaseLocations.CommonApplicationData, "")
        cmdIcoShared.Tag = SharedIcoLocation
        totHelp.SetToolTip(cmdIcoShared, SharedIcoLocation.Path & vbCrLf & My.Resources.ClickForBrowse)
        If My.Application.IsNetworkDeployed Then
            optLocProgramFiles.Enabled = False
            optIcoProgramFiles.Enabled = False
            cmdDBProgramFiles.Enabled = False
            cmdIcoProgramFiles.Enabled = False
        End If
        'Cultures
        cmbLanguage.Items.Clear()
        Dim CurrLoc As Integer = -1
        Dim i As Integer = 0
        cmbLanguage.DisplayMember = "DisplayName"
        cmbLanguage.ValueMember = "Name"
        For Each loc As Globalization.CultureInfo In GetLocalizations()
            cmbLanguage.Items.Add(loc)
            If My.Application.UICulture.LCID = loc.LCID Then CurrLoc = i
            i += 1
        Next loc
        If CurrLoc <> -1 Then
            cmbLanguage.SelectedIndex = CurrLoc
        Else
            cmbLanguage.SelectedIndex = 0
        End If
    End Sub

    Public Shared Function GetLocalizations() As List(Of Globalization.CultureInfo)
        Dim TrnsList As New List(Of Globalization.CultureInfo)
        Try
            TrnsList.Add(New Globalization.CultureInfo(CType(System.Reflection.Assembly.GetCallingAssembly.GetCustomAttributes(GetType(Resources.NeutralResourcesLanguageAttribute), False)(0), Resources.NeutralResourcesLanguageAttribute).CultureName))
        Catch
            TrnsList.Add(New Globalization.CultureInfo(""))
        End Try
        Try
            For Each dir As String In IO.Directory.GetDirectories(My.Application.Info.DirectoryPath)
                Try
                    Dim LocName As String = IO.Path.Combine(dir, IO.Path.GetFileNameWithoutExtension(Reflection.Assembly.GetCallingAssembly.ManifestModule.Name) & ".resources.dll")
                    If IO.File.Exists(LocName) Then
                        Try
                            Dim Asm As System.Reflection.Assembly = Reflection.Assembly.LoadFrom(LocName)
                            If Asm.GetName.Name = IO.Path.GetFileNameWithoutExtension(Reflection.Assembly.GetCallingAssembly.ManifestModule.Name) & ".resources" Then TrnsList.Add(New Globalization.CultureInfo(IO.Path.GetFileName(dir)))
                        Catch : End Try
                    End If
                Catch : End Try
            Next dir
        Catch : End Try
        Return TrnsList
    End Function

    Private Sub cmdPath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdIcoUser.Click, cmdIcoShared.Click, cmdIcoProgramFiles.Click, cmdDBUser.Click, cmdDBShared.Click, cmdDBProgramFiles.Click
        Dim TC As String = Nothing
        Try
            TC = IO.Path.Combine(My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\Ghisler\Total Commander", "InstallDir", Nothing), "TOTALCMD.EXE")
        Catch
            Try
                TC = IO.Path.Combine(My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Ghisler\Total Commander", "InstallDir", Nothing), "TOTALCMD.EXE")
            Catch : End Try
        End Try
        Try
            Process.Start(TC, """" & DirectCast(DirectCast(sender, Button).Tag, Tools.IOt.Path).Path & """")
        Catch
            Try
                Process.Start(DirectCast(DirectCast(sender, Button).Tag, Tools.IOt.Path).Path)
            Catch : End Try
        End Try
    End Sub

    Private Sub cmdIcoBw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdIcoBw.Click
        fbdIcoLoc.SelectedPath = txtIcoUserDefined.Text
        If fbdIcoLoc.ShowDialog = Windows.Forms.DialogResult.OK Then
            txtIcoUserDefined.Text = fbdIcoLoc.SelectedPath
        End If
    End Sub

    Private Sub cmbLanguage_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbLanguage.SelectedIndexChanged
        Static Suppress As Boolean
        If Suppress Then Exit Sub
        Try
            Suppress = True
            Threading.Thread.CurrentThread.CurrentUICulture = cmbLanguage.SelectedItem
            Dim SelIndex As Integer = cmbLanguage.SelectedIndex
            cmbLanguage.Items.Clear()
            For Each loc As Globalization.CultureInfo In GetLocalizations()
                cmbLanguage.Items.Add(loc)
            Next loc
            cmbLanguage.SelectedIndex = SelIndex
        Finally
            Suppress = False
        End Try
    End Sub
End Class
